package com.zxl.manager.controller;

import com.zxl.manager.entity.WxRes;
import com.zxl.manager.service.ApiService;
import com.zxl.manager.utils.HttpUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by jimmy on 2017/8/13.
 */
@Controller
public class ApiController {

    private Logger logger = Logger.getLogger(ApiController.class);

    @Autowired
    private ApiService apiService;

    @RequestMapping("wxapi")
    @ResponseBody
    public String wxapi(HttpServletRequest request, HttpServletResponse response){
        logger.debug("signature:"+request.getParameter("signature"));
        logger.debug("timestamp:"+request.getParameter("timestamp"));
        logger.debug("nonce:"+request.getParameter("nonce"));
        logger.debug("echostr:"+request.getParameter("echostr"));
        String data = HttpUtil.readReqStr(request);
        logger.debug("data:"+data);
        try {
            JAXBContext context = JAXBContext.newInstance(WxRes.class);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(data);
            WxRes res = (WxRes) unmarshaller.unmarshal(sr);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date = new Date();
            date.setTime(Long.parseLong(res.getCreateTime())*1000);
            String dt = sdf.format(date);
            res.setCreateTime(dt);
            apiService.AnsWxEvent(res,data);
            logger.debug("wxres:"+res.getEventKey());
        }catch (Exception e){
            logger.error("微信XML解析失败",e);
        }

        return "success";
    }
}
